﻿"""User domain model with basic role support."""

from __future__ import annotations

from typing import TYPE_CHECKING

from sqlalchemy import Boolean, Enum, Integer, String
from sqlalchemy.orm import Mapped, mapped_column, relationship

from ..db.base_class import Base
from .base import TimestampMixin

if TYPE_CHECKING:
    from .lead import Lead
    from .password_reset_token import PasswordResetToken
    from .performance_record import PerformanceRecord
    from .visitor_sheet import VisitorSheet


USER_ROLES = ("admin", "project_manager", "consultant", "client")
DEFAULT_ROLE = "consultant"


class User(TimestampMixin, Base):
    """User entity with simple role-based access control."""

    __tablename__ = "users"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
    hashed_password: Mapped[str] = mapped_column(String(255), nullable=False)
    full_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
    role: Mapped[str] = mapped_column(
        Enum(*USER_ROLES, name="userrole"),
        nullable=False,
        default=DEFAULT_ROLE,
    )
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    is_admin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)

    leads: Mapped[list["Lead"]] = relationship(
        back_populates="owner",
        cascade="all, delete-orphan",
    )
    password_reset_tokens: Mapped[list["PasswordResetToken"]] = relationship(
        back_populates="user",
        cascade="all, delete-orphan",
    )
    performance_records: Mapped[list["PerformanceRecord"]] = relationship(
        back_populates="user",
        cascade="all, delete-orphan",
    )
    visitor_sheets: Mapped[list["VisitorSheet"]] = relationship(
        back_populates="agent",
    )
